import request from '@/utils/request'
import { SAVE_EDIT, SAVE_USER } from '../actionType/profile'

/**
 * 触发个人资料
 * @param {*} payload
 * @returns
 */
export const saveUser = (payload) => {
  return {
    type: SAVE_USER,
    payload,
  }
}
/**
 * 触发个人信息（生日等）
 * @param {*} payload
 * @returns
 */
export const saveProfile = (payload) => {
  return {
    type: SAVE_EDIT,
    payload,
  }
}
/**
 * 获取个人资料
 * @returns
 */
export const getUserProfile = () => {
  return async (dispatch) => {
    const res = await request({
      url: '/user',
      method: 'get',
    })
    if (res) {
      dispatch(saveUser(res.data))
    } else {
      dispatch(saveProfile({}))
    }
  }
}

/**
 * 获取个人信息
 * @returns
 */
export const getUserEdit = () => {
  return async (dispatch) => {
    const res = await request({
      url: '/user/profile',
      method: 'get',
    })
    // console.log(res)
    if (res) {
      dispatch(saveProfile(res.data))
    } else {
      dispatch(saveProfile({}))
    }
  }
}

// 修改用户资料
export const editProfile = (data) => {
  return async (dispatch) => {
    await request({
      url: '/user/profile',
      method: 'patch',
      data,
    })
    dispatch(getUserEdit())
  }
}

// 上传图片文件头像
export const addFile = (photo) => {
  return async (dispatch) => {
    await request({
      method: 'patch',
      url: '/user/photo',
      data: photo,
    })
    dispatch(getUserEdit())
  }
}
